import os
import json


def read_chat_history(user_name):
    """
    读取历史对话记录
    :param user_name: 用户名
    :return: 历史对话记录的列表，如果没有记录返回空列表
    """
    history_message_path = f'./data/history/{user_name}_history_message.json'
    print(history_message_path)
    if os.path.exists(history_message_path):
        with open(history_message_path, 'r', encoding='utf-8') as f:
            try:
                history = json.load(f)
                return history[-10:]
            except json.JSONDecodeError:
                return []  # 如果解析失败，返回空列表
    else:
        return []  # 如果文件不存在，返回空列表


def save_chat_history(user_name, message, reply):
    """
    保存历史对话记录
    :param user_name: 用户名
    :param message: 用户信息
    :param reply: ai返回信息
    :return:
    """
    history_message_path = f'./data/history/{user_name}_history_message.json'
    data_dir = os.path.dirname(history_message_path)

    # 如果路径不存在，创建路径
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    chat_record = {
        "message": message,
        "reply": reply
    }

    # 读取历史记录
    history = read_chat_history(user_name)

    # 添加新记录
    history.append(chat_record)

    # 写入文件
    with open(history_message_path, 'w', encoding='utf-8') as f:
        json.dump(history, f, indent=4, ensure_ascii=False)

if __name__ == '__main__':
    pass